package capricornus.components.utils.mouse
{
	import flash.display.InteractiveObject;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;

	/**
	 * 鼠标按下控制器 
	 * @author kael
	 * 
	 */	
	internal class MousePressController
	{
		private var _stage:Stage;
		
		private var _isListen:Boolean = true;
		private var _dis:InteractiveObject;
		
		public function MousePressController( dis:InteractiveObject )
		{
			_dis = dis;
			init();
		}
		
		private function init():void
		{
			_isListen = true;
			_dis.addEventListener( MouseEvent.MOUSE_DOWN, onMouseDown, false, 0, true );
		}
		
		public function destroy():void
		{
			if( _isListen )
			{
				_dis.removeEventListener( MouseEvent.MOUSE_DOWN, onMouseDown );
			}
			else
			{
				_dis.removeEventListener( MouseEvent.ROLL_OUT, onRollOut );
				_dis.removeEventListener( MouseEvent.MOUSE_UP, onRollOut );
				_stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame );
			}
			
			_stage = null;
			_dis = null;
		}
		
		private function onMouseDown( e:MouseEvent ):void
		{
			_stage = _dis.stage;
			
			_isListen = false;
			_dis.removeEventListener( MouseEvent.MOUSE_DOWN, onMouseDown );
			
			_dis.addEventListener( MouseEvent.ROLL_OUT, onRollOut, false, 0, true );
			_dis.addEventListener( MouseEvent.MOUSE_UP, onRollOut, false, 0, true );
			_stage.addEventListener( Event.ENTER_FRAME, onEnterFrame, false, 0, true );
		}
		
		private function stop():void
		{
			_isListen = true;
			
			_dis.addEventListener( MouseEvent.MOUSE_DOWN, onMouseDown, false, 0, true );
			
			_dis.removeEventListener( MouseEvent.ROLL_OUT, onRollOut );
			_dis.removeEventListener( MouseEvent.MOUSE_UP, onRollOut );
			_stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
		
		private function onRollOut( e:MouseEvent ):void
		{
			stop();
		}
		
		private function onEnterFrame( e:Event ):void
		{
			_dis.dispatchEvent( new MouseEvent( MouseEvent.MOUSE_DOWN, false ) );
		}
	}
}